package com.xc.demo.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.xc.demo.entity.Files;
import com.xc.demo.mapper.FileMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;

@Slf4j
@RestController
@RequestMapping("/file")
public class FileConrtoller {

    @Resource
    private FileMapper fileMapper;

    @Value("${files.upload.path}")
    private String fileUploadPath;


    @PostMapping("/upload")
    public String upload(@RequestParam MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String type = FileUtil.extName(originalFilename);
        long size = file.getSize();
        File uploadParentFile = new File(fileUploadPath);
        if(!uploadParentFile.exists()){
            uploadParentFile.mkdirs();
        }
//        定义一个唯一的文件标识码，防止文件路径相同不能区分
        String uuid=IdUtil.fastSimpleUUID();
        String fileUuid = uuid + StrUtil.DOT +type;
        File uploadFile = new File(fileUploadPath + fileUuid);



//        把获取到的文件先存储到磁盘
        file.transferTo(uploadFile);

        String url = "http://localhost:9090/file/" + fileUuid;

//        存储到数据库
         Files saveFile = new Files();
         saveFile.setName(originalFilename);
         saveFile.setType(type);
         saveFile.setSize(size/1024);
         saveFile.setUrl(url);
         fileMapper.insert(saveFile);

        return url;
    }

    /**
     * 文件下载接口 http://localhost:9090/file/{fileUuid}
     * @param fileUuid
     * @param response
     * @throws IOException
     */
    @GetMapping("/{fileUuid}")
    public void  download(@PathVariable String fileUuid, HttpServletResponse response) throws IOException {
//        根据文件的唯一标识码获取文件
        File uploadFile = new File(fileUploadPath + fileUuid);
//        设置输出流的格式
        ServletOutputStream os = response.getOutputStream();
        response.addHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileUuid,"UTF-8"));
        response.setContentType("application/octet-stream");

//        读取文件字节流
        os.write(FileUtil.readBytes(uploadFile));
        os.flush();
        os.close();
    }












}
